package com.dream.service.user.util;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.dream.common.toolkits.cache.RedisCache;
import com.dream.service.user.config.TokenConfig;
import com.dream.service.user.domain.entity.Token;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.nio.charset.Charset;

/**
 * Created by kangdong on 16/3/24.
 */
public class UserToken {
    //redis
    private  static RedisCache redisCache = RedisCache.getInstance("user_redis_address");

    private static  final  String secretKey="#*#($Motif)(+_?}{<";

    private static Charset UTF8 = Charset.forName("utf-8");

    public static Token generateToken(String uuid,String pin){
        if (StringUtils.isEmpty(uuid)){
            return  null;
        }
        //先读缓存
        byte[] tokenRedis  = redisCache.getFromCache(TokenConfig.TokenCacheKeyPrefix.concat(pin).getBytes());

        Token token;
        if(tokenRedis==null){
            long currentTime =  System.currentTimeMillis();
            HashFunction hashFunction=Hashing.murmur3_128();
            CharSequence charSequence= uuid + secretKey + currentTime;
            HashCode hashCode = hashFunction.hashString(charSequence, UTF8);
            token = new Token(hashCode.toString(),currentTime, TokenConfig.TOKEN_VALID_TIME);
            //  写入缓存，以 pin 为 key
            redisCache.setToCache(TokenConfig.TokenCacheKeyPrefix.concat(pin).getBytes(), TokenConfig.TOKEN_VALID_TIME, token.getValue().getBytes());
        }else {
            long currentTime =  System.currentTimeMillis();
            //更新时间
            redisCache.setToCache(TokenConfig.TokenCacheKeyPrefix.concat(pin).getBytes(), TokenConfig.TOKEN_VALID_TIME, tokenRedis);
            token = new Token(new String(tokenRedis),currentTime, TokenConfig.TOKEN_VALID_TIME);
        }
        redisCache.setToCache(TokenConfig.TokenCacheKeyPrefix.concat(pin).getBytes(), TokenConfig.TOKEN_VALID_TIME, token.getValue().getBytes());
        return token;
    }

    public static String createToken(String arg){
        HashFunction hashFunction=Hashing.murmur3_128();
        CharSequence charSequence= arg + secretKey;
        HashCode hashCode = hashFunction.hashString(charSequence,UTF8);
        return hashCode.toString();
    }

    public static int hashingAsInt(String pin){
        HashFunction hashFunction=Hashing.murmur3_128();
        HashCode hashCode = hashFunction.hashString(pin, UTF8);
        return hashCode.asInt();
    }

    public static long tokenTtl(String pin){
        return redisCache.ttl(TokenConfig.TokenCacheKeyPrefix.concat(pin));
    }

    public static void main(String[] args) {
        System.out.println(hashingAsInt("f8aeeb7605be4704898a195bf8b4c791"));

        System.out.println(tokenTtl("9caa597ece1a4b9193dc39dbb13e968d"));
    }
}
